package com.easepal802s.project.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.easepal802s.project.R;
import com.easepal802s.project.ble.BleController;
import com.easepal802s.project.ble.BleService;
import com.easepal802s.project.ble.BtDevice;
import com.easepal802s.project.observer.BleDataObserver;
import com.easepal802s.project.ui.presenter.HomePresenter;
import com.easepal802s.project.ui.iview.IHomeView;
import com.easepal802s.project.utils.ActivityUtils;
import com.easepal802s.project.widget.LayoutNormalTitle;
import com.example.reslib.utils.ToastUtils;
import com.ogawa.base.utils.CommonUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import static com.easepal802s.project.ble.BleController.CONNECT_BREAK;
import static com.easepal802s.project.ble.BleController.CONNECT_FAIL;
import static com.easepal802s.project.ble.BleController.CONNECT_ING;
import static com.easepal802s.project.ble.BleController.CONNECT_SUCCEED;

/**
 * 首页
 */
public class HomeActivity extends BaseMvpTestActivity<HomePresenter,HomeActivity> implements View.OnClickListener, IHomeView , BleDataObserver.OnBleListerner {
    private boolean isExit;
    private LayoutNormalTitle mLayoutTitle;
    private MyHandler myHandler;
    private String isBreak = "NONE";
    private String flag = "BREAK";



    @Override
    public HomePresenter initPresenter() {
        return  new HomePresenter(this);
    }

    @Override
    protected void initCreateView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        myHandler = new MyHandler(this);
        BleDataObserver.getInst().registerBleDataObserver(this);
        initView();
    }
    //Activity的启动模式(launchMode),通过这个方法接受Intent
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isBreak = intent.getStringExtra("isbreak");
        if(!TextUtils.isEmpty(isBreak)&&isBreak.equals(flag)){
            showsAlert(R.string.link_break,false);
        }
    }


    @Override
    public HomeActivity initActivity() {
        return this;
    }


    private void initView() {
        Log.e("whitch","802");
        mLayoutTitle = findViewById(R.id.activity_home_title);
        mLayoutTitle.setTitleNameGone();
        mLayoutTitle.setBackGone();
        findViewById(R.id.linear_attitude_adjustment).setOnClickListener(this);
        findViewById(R.id.linear_high_massage).setOnClickListener(this);
        findViewById(R.id.linear_professional_massage).setOnClickListener(this);


    }



    @Override
    protected void onStart() {
        super.onStart();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁服务。
        BleDataObserver.getInst().removeBleDataObserver(this);
        mLayoutTitle.onDestory();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.linear_attitude_adjustment:
                if(BleController.getInst().getIsOn()&&BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                    ActivityUtils.startAttitudeAdjustmentActivity(this);
                }
                else {
                    if(BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                        ToastUtils.showShortToastPowerOff(this);
                    }
                    else {
                        ToastUtils.showShortToastBreak(this);
                    }
                }

                break;
            case R.id.linear_high_massage:
                //高级按摩
                if(BleController.getInst().getIsOn()&&BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                    ActivityUtils.startAdvancedMassageActivity(this);
                }
                else {
                    if(BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                        ToastUtils.showShortToastPowerOff(this);
                    }
                    else {
                        ToastUtils.showShortToastBreak(this);
                    }

                }


                break;
            case R.id.linear_professional_massage:
                //专业按摩
                if(BleController.getInst().getIsOn()&&BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                    ActivityUtils.startProfessionMassaActivity(this);
                }
                else {
                    if(BleController.getInst().getConnectState()==CONNECT_SUCCEED){
                        ToastUtils.showShortToastPowerOff(this);
                    }
                    else {
                        ToastUtils.showShortToastBreak(this);
                    }
                }

                break;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }

    /**
     * 双击退出
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000);
        } else {

            finish();
            System.exit(0);
        }
    }




    @Override
    public void getData(boolean isOn) {
        if(isOn){
            myHandler.obtainMessage(0).sendToTarget();

        }
        else {
            myHandler.obtainMessage(1).sendToTarget();
        }

    }

    @Override
    public void onConnectState(int state) {
        Log.e("onConnectState",state+"");
        if(state ==CONNECT_ING){
           showkProgress(R.string.bluetooth_connecting);

        }
        else if(state == CONNECT_FAIL){
            showToast(R.string.device_link_fail);
        }
        else if(state == CONNECT_SUCCEED){

                canclekProgress();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //android8.0以上通过startForegroundService启动service
                startForegroundService(new Intent(this, BleService.class));
            } else {
                startService(new Intent(this, BleService.class));
            }

//                startService(new Intent(this, BleService.class));
                showToast(R.string.bluetooth_connected);
        }
    }

    @Override
    public void onTargetDeviceFind(BleDevice bleDevice) {
        canclekProgress();
        if(bleDevice ==null){
            showToast(R.string.bluetooth_timeout);
        }
        else {
            BtDevice mBtDevice = new BtDevice(bleDevice.getName(), bleDevice);
            mDeviceList.add(mBtDevice);
            ShowBTListDialog(mDeviceList);
        }
    }

    @Override
    public void onStarScan() {
        mDeviceList.clear();
        showkProgress(R.string.bluetooth_scan);
    }

    @Override
    public void onNoDeviceFind() {
        showToast(R.string.bluetooth_nofind);
    }

    @Override
    public void onGetData(String data) {
        mBasePresenter.getDatas(data);
    }

    @Override
    public void onPowerOff() {
        if(CommonUtil.isActivityTop(this.getClass(),this)){
            if (BleController.getInst().getConnectState() == CONNECT_BREAK) {
                showsAlert(R.string.link_break, false);
            }
        }


    }

    @Override
    public void onDataChange(String bage, int auto, int skill, int air,String name,String commond) {

    }

    @Override
    public void onShoulderAdjust(int data) {
        if(CommonUtil.isActivityTop(this.getClass(),this)&&data==1){
            ActivityUtils.startShouldersAdjustmentActivity(this);
        }
    }

    private  class MyHandler extends Handler {
        WeakReference<HomeActivity> mMainActivityWeakReference;

        MyHandler(HomeActivity mHomeActivity) {
            mMainActivityWeakReference = new WeakReference<>(mHomeActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            final HomeActivity mHomeActivity = mMainActivityWeakReference.get();
            if (mHomeActivity != null) {
                switch (msg.what) {
                    case 0:
                        mLayoutTitle.setPowerOn(true);
                        break;
                    case 1:
                        mLayoutTitle.setPowerOn(false);
                        break;


                }
            }
        }
    }


}
